package com.example.base.demo.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

/**
 * @author TangDan
 * @version 1.0
 * @since 2023/3/3
 */
//@JsonComponent
public class MyJsonComponent001 {

    public static class Serializer extends JsonSerializer<User> {

        /**
         * 序列化定制
         */
        @Override
        public void serialize(User value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
            jgen.writeStartObject();
            jgen.writeStringField("name", "张小小");
            jgen.writeNumberField("age", value.getAge());
            jgen.writeEndObject();
        }

    }

    public static class Deserializer extends JsonDeserializer<User> {
        /**
         * 反序列化定制
         */
        @Override
        public User deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
            ObjectCodec codec = jsonParser.getCodec();
            JsonNode tree = codec.readTree(jsonParser);
            String name = tree.get("name").textValue();//
            int age = tree.get("age").intValue();
            return new User("张中中", age);
        }
    }
}
